﻿using System;
using System.Collections.Generic;
using System.Linq;
using GC_RF.BusinessEntities.DTOs;
using GC_RF.DataAccess.Abstractions.Interfaces.Factories;
using GC_RF.DataAccess.Abstractions.Interfaces.Helpers;
using GC_RF.DataAccess.Abstractions.Interfaces.Repositories;
using GC_RF.DataAccess.Models;
using GC_RF.Domain.Abstractions.Interfaces.Services;
using GC_RF.Domain.Abstractions.Services;

namespace GC_RF.Domain.Services
{
	public class NewsService : BaseService, INewsService
	{
		#region Variables

		private readonly INewsRepository _newsRepository;

		#endregion

		#region Constructors

		public NewsService(IUnitOfWork unitOfWork, IRepositoryFactory repositoryFactory)
			: base(unitOfWork, repositoryFactory)
		{
			_newsRepository = RepositoryFactory.CreateNewsRepository();
			if (_newsRepository == null)
				throw new ArgumentNullException(string.Format("newsRepository"));
		}

		#endregion

		#region INewsService Members

		public IEnumerable<NewsData> GetNews(int pageNumber, int countNews)
		{
			return _newsRepository.TakeQuery(
				q => q.OrderByDescending(n => n.Date),
				pageNumber*countNews, countNews,
				n => new NewsData
				{
					Title = n.Title,
					Id = n.Id,
					Description = n.Description,
					Preview = n.Preview,
					Date = n.Date,
					ImageUrl = n.ImageUrl
				});
		}

		public int NewsCount()
		{
			return _newsRepository.Count();
		}

		public void Save(NewsData data)
		{
			if (data == null) return;

			var entity = new News();
			if (data.Id > 0)
				entity = _newsRepository.Query(n => n.Id == data.Id).FirstOrDefault();

			if (entity == null) return;

			entity.Date = data.Date;
			entity.Description = data.Description;
			entity.ImageUrl = data.ImageUrl;
			entity.Preview = data.Preview;
			entity.Title = data.Title;

			if (entity.Id == 0)
				_newsRepository.Add(entity);

			UnitOfWork.SaveChanges();
		}

		#endregion
	}
}
